#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2022/10/26 10:27
# @Author  : 招财大龙猫
# @File    : file_db_oper.py
# @Description : 文件操作类

class DBConnectionManager:
    """
    数据库操作管理类
    """

    def __init__(self, hostname, port):
        self.hostname = hostname
        self.port = port
        self.connection = None

    def __enter__(self):
        self.connection = DBClient(self.hostname, self.port)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.close()


class FileManager:
    """
    文件操作管理类
    """

    def __init__(self, name, mode):
        print('calling __init__ method')
        self.name = name
        self.mode = mode
        self.file = None

    def __enter__(self):
        print('calling __enter__ method')
        self.file = open(self.name, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('calling __exit__ method')
        if self.file:
            self.file.close()


from contextlib import contextmanager


@contextmanager
def file_manager(name, mode):
    try:
        f = open(name, mode)
        yield f
    finally:
        f.close()


with file_manager('test.txt', 'w') as f:
    f.write('hello world')
